# -*- coding:utf-8 -*-
import struct,Pluto,fnmatch,os,codecs,re

def makestr(i):
    string=[]
    j=0
    while j>=0:
        if re.match(u'－'*18,lines[i+2+j]):
            break
        string.append(lines[i+2+j])
        j+=1
    return ''.join(string)[:-2]

fl=Pluto.walk('Text2')
for fn in fl:
    if not fnmatch.fnmatch(fn,'*.txt'):
        continue
    print fn
    fp=codecs.open(fn,'rb','utf16')
    lines=fp.readlines()
    fp.close()
    line_num=len(lines)

    text_list=[]
    for i in xrange(line_num):
        if re.match('No.\d+',lines[i]):
            text=makestr(i)
            text_list.append(text)
    num=len(text_list)

    tar=open(fn[:-4],'wb')
    tar.write('\x01\x00\x00\x00\x0c\x00\x00\x00')
    tar.seek(0xc+num*4)
    offsetlist=[]
    lengthlist=[]
    for txt in text_list:
        startoffset=tar.tell()
        offsetlist.append(startoffset-0xc)
        print txt
        print '-'*20
        txt=txt.replace('\r\n','',1)
        length=len(txt)
        j=0
        while j<length:
            if txt[j]==u'{':
                word=struct.pack('H',eval('0x'+txt[j+1]+txt[j+2]+txt[j+3]+txt[j+4]))
                tar.write(word)
                j+=6
            elif txt[j]=='\r':
                tar.write('\x0a\x00')
                j+=2
            else:
                tar.write(txt[j].encode('utf16')[2:])
                j+=1
        endoffset=tar.tell()
        lengthlist.append((endoffset-startoffset-0xe)/2)

    size=tar.tell()
    tar.seek(0x8)
    tar.write(struct.pack('i',size))

    for k in xrange(num):
        tar.seek(0xc+k*4)
        tar.write(struct.pack('i',offsetlist[k]))
        tar.seek(offsetlist[k]+0xc+0x8)
        tar.write(struct.pack('i',lengthlist[k]))
    tar.close()